package com.example.ivideo_2211a.adapter

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.example.ivideo_2211a.databinding.ItemUserLivePreviewBinding
import android.view.View
import com.example.ivideo_2211a.fg.ZBFragment

/**
 * 用户直播预览适配器
 * 用于显示用户直播预览卡片列表
 */
class UserLivePreviewAdapter : ListAdapter<ZBFragment.UserLivePreview, UserLivePreviewAdapter.ViewHolder>(UserLivePreviewDiffCallback()) {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val binding = ItemUserLivePreviewBinding.inflate(
            LayoutInflater.from(parent.context),
            parent,
            false
        )
        return ViewHolder(binding)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.bind(getItem(position))
    }

    inner class ViewHolder(private val binding: ItemUserLivePreviewBinding) : RecyclerView.ViewHolder(binding.root) {

        fun bind(userLivePreview: ZBFragment.UserLivePreview) {
            binding.apply {
                // 设置用户名
                // 注意：这里需要根据实际的item布局来设置
                // 由于item布局中用户名是硬编码的"Laddy"，这里暂时不设置
                
                // 设置头像背景颜色
                val avatarBackground = root.findViewById<View>(com.example.ivideo_2211a.R.id.avatarBackground)
                avatarBackground?.setBackgroundResource(userLivePreview.avatarBackground)
            }
        }
    }

    /**
     * DiffUtil回调，用于高效更新列表
     */
    private class UserLivePreviewDiffCallback : DiffUtil.ItemCallback<ZBFragment.UserLivePreview>() {
        override fun areItemsTheSame(oldItem: ZBFragment.UserLivePreview, newItem: ZBFragment.UserLivePreview): Boolean {
            return oldItem.username == newItem.username
        }

        override fun areContentsTheSame(oldItem: ZBFragment.UserLivePreview, newItem: ZBFragment.UserLivePreview): Boolean {
            return oldItem == newItem
        }
    }
}
